package com.qiudao.multipleDataSource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * Description: 配置多数据源_iot
 * @author: gdc
 * @date: 2019/10/9
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = {"com.qiudao.multipleDataSource.mapper.iot"}, sqlSessionFactoryRef = "sqlSessionFactoryIot")
public class MybatisDbIotConfig {

    @Value("${mapper-locations.iot}")
    private String mapperLocation;

    /**
     * 注入数据源 bean
     */
    @Bean(name = "iot")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSourceIot() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 注入数据工厂 bean，需要添加指定的数据库
     */
    @Bean
    public SqlSessionFactory sqlSessionFactoryIot() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceIot());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
        return factoryBean.getObject();
    }

    /**
     * 注入模板 bean ,需要添加指定的数据工厂
     */
    @Bean
    public SqlSessionTemplate sqlSessionTemplateIot() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryIot());
    }
}
